package com.dhcc.bpm.modules.scf.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MapApiExampleUtil {
    public static String getAddressInfo(String address) {
        try {
            // 你的接口地址
            String apiUrl = "https://apis.map.qq.com/jsapi";

            // 构造完整的请求URL
            String requestUrl = apiUrl + "?qt=geoc&addr=" + address + "&key=UGMBZ-CINWR-DDRW5-W52AK-D3ENK-ZEBRC&output=jsonp&pf=jsapi&ref=jsapi";

            // 创建 URL 对象
            URL url = new URL(requestUrl);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 获取响应码
            int responseCode = connection.getResponseCode();

            // 获取响应头中的字符集信息
            String contentType = connection.getHeaderField("Content-Type");
            String charset = StandardCharsets.UTF_8.name(); // 默认使用UTF-8
            if (contentType != null && contentType.contains("charset=")) {
                Pattern pattern = Pattern.compile("charset=([\\w-]+)");
                Matcher matcher = pattern.matcher(contentType);
                if (matcher.find()) {
                    charset = matcher.group(1);
                }
            }

            // 读取响应
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
            StringBuilder response = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            // 关闭连接和输入流
            reader.close();
            inputStream.close();
            connection.disconnect();

            // 将 JSON 字符串转为 JsonNode 对象
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.toString());
            // 获取 "province" 键对应的值
            JsonNode provinceNode = jsonNode.path("detail").path("province");
            String province = provinceNode.asText();
            // 返回响应结果
            return province;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
